import os
import uuid
import time
import logging
import folder_paths
import numpy as np
import torch
from PIL import Image, ImageOps, ImageSequence
import node_helpers

# 配置日志
logger = logging.getLogger('PSDModifier')


class LoadImageWithPathInfo:
    """
    加载图像并提取路径信息节点
    支持图像上传功能，加载图像并提取文件名相关信息
    参考Load Images (Upload)节点实现
    """
    @classmethod
    def INPUT_TYPES(s):
        input_dir = folder_paths.get_input_directory()
        files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
        files = folder_paths.filter_files_content_types(files, ["image"])
        return {
            "required": {
                "image": (sorted(files), {"image_upload": True})
            }
        }

    CATEGORY = "image/utils"
    RETURN_TYPES = ("IMAGE", "MASK", "STRING", "STRING", "STRING", "STRING")
    RETURN_NAMES = ("IMAGE", "MASK", "full_path", "filename", "extension", "filename_no_ext")
    FUNCTION = "load_image_with_info"

    def load_image_with_info(self, image):
        """
        加载图像并提取路径信息
        
        参数:
            image: 图像文件名或路径
            
        返回:
            tuple: 包含图像张量、蒙版和文件信息的元组
        """
        # 获取带注释的文件路径
        image_path = folder_paths.get_annotated_filepath(image)
        
        # 加载图像
        img = node_helpers.pillow(Image.open, image_path)
        
        output_images = []
        output_masks = []
        w, h = None, None
        
        excluded_formats = ['MPO']
        
        for i in ImageSequence.Iterator(img):
            i = node_helpers.pillow(ImageOps.exif_transpose, i)
            
            if i.mode == 'I':
                i = i.point(lambda i: i * (1 / 255))
            image = i.convert("RGB")
            
            if len(output_images) == 0:
                w = image.size[0]
                h = image.size[1]
            
            if image.size[0] != w or image.size[1] != h:
                continue
            
            image = np.array(image).astype(np.float32) / 255.0
            image = torch.from_numpy(image)[None,]
            if 'A' in i.getbands():
                mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
                mask = 1. - torch.from_numpy(mask)
            elif i.mode == 'P' and 'transparency' in i.info:
                mask = np.array(i.convert('RGBA').getchannel('A')).astype(np.float32) / 255.0
                mask = 1. - torch.from_numpy(mask)
            else:
                mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
            output_images.append(image)
            output_masks.append(mask.unsqueeze(0))
        
        if len(output_images) > 1 and img.format not in excluded_formats:
            output_image = torch.cat(output_images, dim=0)
            output_mask = torch.cat(output_masks, dim=0)
        else:
            output_image = output_images[0]
            output_mask = output_masks[0]
        
        # 提取文件信息
        full_path = os.path.abspath(image_path)
        filename = os.path.basename(full_path)
        _, extension = os.path.splitext(filename)
        extension = extension.lower().lstrip('.')
        filename_no_ext = os.path.splitext(filename)[0]
        
        logger.info(f"LoadImageWithPathInfo: 加载图像并提取信息 - 完整路径: {full_path}, 文件名: {filename}, 扩展名: {extension}, 无扩展名文件名: {filename_no_ext}")
        
        return (output_image, output_mask, full_path, filename, extension, filename_no_ext)
    
    @classmethod
    def IS_CHANGED(s, image):
        """\检测图像文件是否发生变化"""
        import hashlib
        image_path = folder_paths.get_annotated_filepath(image)
        m = hashlib.sha256()
        with open(image_path, 'rb') as f:
            m.update(f.read())
        return m.digest().hex()

# 注册节点
NODE_CLASS_MAPPINGS = {
    "LoadImageWithPathInfo": LoadImageWithPathInfo
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "LoadImageWithPathInfo": "Load Image With Path Info"
}